package api

import (
	"ao/app/request"
	"ao/app/service"
	commonApi "ao/common/api"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gvalid"
	"sync"
)

var DeviceInfo = DeviceInfoApi{}
var mx sync.Mutex
type DeviceInfoApi struct {
	commonApi.CommonBase
}

// Index is a demonstration route handler for output "Hello World!".
func (c *DeviceInfoApi) List(r *ghttp.Request) {
	//表单验证
	var apiReq *request.DeviceReportSearchReq
	if err := r.Parse(&apiReq); err != nil {
		c.FailJsonExit(r, err.(gvalid.Error).Current().Error())
	}
	pageSize, total, page, list, err := service.DeviceInfo.List(apiReq)
	if err != nil {
		c.FailJsonExit(r, err.Error())
	}
	//deviceLast:=service.DeviceLast
	//for k,v := range list{
	//	lasttime := deviceLast[v.IMEI].Lasttime
	//	if lasttime !="" {
	//		list[k].Lasttime=lasttime
	//		list[k].Posy=deviceLast[v.IMEI].Posy
	//		list[k].Posx=deviceLast[v.IMEI].Posx
	//		list[k].Posh=deviceLast[v.IMEI].Posh
	//		list[k].Onlinetcp=deviceLast[v.IMEI].Onlinetcp
	//	}
	//}
	r.Response.WriteJson(g.Map{
		"current": page,
		"total":   total,
		"pages":   (total / pageSize) + 1,
		"size":    pageSize,
		"records": list,
	})
}
func (c *DeviceInfoApi) GroupList(r *ghttp.Request) {
	//表单验证
	var apiReq *request.DeviceReportSearchReq
	if err := r.Parse(&apiReq); err != nil {
		c.FailJsonExit(r, err.(gvalid.Error).Current().Error())
	}
	_, total, _, list, err := service.DeviceInfo.GroupList(apiReq)
	if err != nil {
		c.FailJsonExit(r, err.Error())
	}


	//for k,_ := range list{
	//	Posx, _:=service.DeviceLast.Load("Posx")
	//	Onlinetcp,_ :=service.DeviceLast.Load("Onlinetcp")
	//	Posh, _ :=service.DeviceLast.Load("Posh")
	//	Lasttime, ok :=service.DeviceLast.Load("Lasttime")
	//	Posy, _ :=service.DeviceLast.Load("Posy")
	//	glog.Infof("store Lasttime:%v",Lasttime)
	//	if  ok {
	//		list[k].Lasttime=gconv.String(Lasttime)
	//		list[k].Posy=gconv.String(Posy)
	//		list[k].Posx=gconv.String(Posx)
	//		list[k].Posh=gconv.String(Posh)
	//		list[k].Onlinetcp=gconv.Int(Onlinetcp)
	//	}
	//}
	onlineCount, _ := g.Model("device_info").Where("groupId", "88888").WhereIn("onlinetcp", 1).Count()
	records :=make(map[int]interface{})
	records[0] =  DeviceGroup{
		Name:        list[0].GroupName,
		Count:       total,
		OnlineCount: onlineCount,
		Devices:     list}
	r.Response.WriteJson(g.Map{
		"records": records,
	})
}

type DeviceGroup struct {
	Name        string            `json:"name"`
	Count       int               `json:"count"`
	OnlineCount int               `json:"online_count"`
	Devices     []*request.Device `json:"devices"`
}
